<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设备状态实时监控</title>
    <script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@7.0.0/dist/browser/signalr.min.js"></script>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            border-bottom: 3px solid #4CAF50;
            padding-bottom: 10px;
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            font-weight: bold;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .message-list {
            max-height: 500px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            margin-top: 20px;
            background-color: #fafafa;
        }
        .message-item {
            padding: 10px;
            margin: 5px 0;
            background: white;
            border-left: 4px solid #4CAF50;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .message-time {
            color: #666;
            font-size: 0.9em;
            margin-bottom: 5px;
        }
        .message-content {
            color: #333;
        }
        .equipment-list {
            color: #0066cc;
            font-weight: bold;
            margin-top: 5px;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin: 5px;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .info {
            background-color: #e7f3ff;
            padding: 15px;
            border-radius: 4px;
            margin: 15px 0;
            border-left: 4px solid #2196F3;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 设备状态实时监控</h1>
        
        <div class="info">
            <strong>说明：</strong>后台服务每分钟自动检查设备状态，如果设备已完成所有排程且无待处理订单，将自动更新为空闲状态。
        </div>

        <div>
            <button id="connectBtn" onclick="connect()">连接服务器</button>
            <button id="disconnectBtn" onclick="disconnect()" disabled>断开连接</button>
        </div>

        <div id="connectionStatus" class="status disconnected">
            ⚠️ 未连接
        </div>

        <h2>📋 更新记录</h2>
        <div id="messages" class="message-list">
            <p style="color: #999; text-align: center;">等待接收消息...</p>
        </div>
    </div>

    <script>
        let connection = null;

        async function connect() {
            try {
                // 创建SignalR连接
                connection = new signalR.HubConnectionBuilder()
                    .withUrl("/equipmentStatusHub")
                    .withAutomaticReconnect()
                    .configureLogging(signalR.LogLevel.Information)
                    .build();

                // 监听设备状态更新消息
                connection.on("ReceiveEquipmentStatusUpdate", (data) => {
                    console.log("收到设备状态更新:", data);
                    addMessage(data);
                });

                // 连接状态变化
                connection.onreconnecting(() => {
                    updateStatus("reconnecting", "🔄 正在重新连接...");
                });

                connection.onreconnected(() => {
                    updateStatus("connected", "✅ 已重新连接");
                });

                connection.onclose(() => {
                    updateStatus("disconnected", "⚠️ 连接已断开");
                    document.getElementById("connectBtn").disabled = false;
                    document.getElementById("disconnectBtn").disabled = true;
                });

                // 开始连接
                await connection.start();
                console.log("SignalR 连接成功");
                updateStatus("connected", "✅ 已连接到服务器");
                document.getElementById("connectBtn").disabled = true;
                document.getElementById("disconnectBtn").disabled = false;

            } catch (err) {
                console.error("连接失败:", err);
                updateStatus("disconnected", "❌ 连接失败: " + err.message);
            }
        }

        async function disconnect() {
            if (connection) {
                await connection.stop();
                console.log("SignalR 连接已断开");
            }
        }

        function updateStatus(status, message) {
            const statusDiv = document.getElementById("connectionStatus");
            statusDiv.className = "status " + (status === "connected" ? "connected" : "disconnected");
            statusDiv.textContent = message;
        }

        function addMessage(data) {
            const messagesDiv = document.getElementById("messages");
            
            // 清除初始提示
            if (messagesDiv.querySelector('p[style*="color: #999"]')) {
                messagesDiv.innerHTML = '';
            }

            const messageDiv = document.createElement("div");
            messageDiv.className = "message-item";
            
            const time = data.Time ? new Date(data.Time).toLocaleString('zh-CN') : new Date().toLocaleString('zh-CN');
            
            messageDiv.innerHTML = `
                <div class="message-time">⏰ ${time}</div>
                <div class="message-content">${data.Message || JSON.stringify(data)}</div>
                ${data.Equipments && data.Equipments.length > 0 ? 
                    `<div class="equipment-list">📦 设备: ${data.Equipments.join(', ')}</div>` : ''}
            `;
            
            messagesDiv.insertBefore(messageDiv, messagesDiv.firstChild);

            // 限制显示最近50条消息
            while (messagesDiv.children.length > 50) {
                messagesDiv.removeChild(messagesDiv.lastChild);
            }
        }

        // 页面加载时自动连接
        window.addEventListener('load', () => {
            console.log("页面已加载，准备连接SignalR...");
        });
    </script>
</body>
</html>
